package com.zbkj.service.settlement;

import cn.hutool.core.util.StrUtil;
import com.beust.jcommander.internal.Lists;
import com.zbkj.dal.base.constants.BrokerageRecordConstants;
import com.zbkj.dal.base.constants.GlobalConstants;
import com.zbkj.dal.entity.merchant.Merchant;
import com.zbkj.dal.entity.order.DuesOrder;
import com.zbkj.dal.entity.user.User;
import com.zbkj.dal.entity.user.UserBrokerageRecord;
import com.zbkj.service.service.DuesOrderService;
import com.zbkj.service.service.MerchantService;
import com.zbkj.service.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * 会员升级佣金结算
 * @author tianzhonghai
 * 2023/10/6 13:23
 */
@SettleTypeAnno(value = SettlementConstants.UPGRADE)
@Component
@Slf4j
public class DuesSettleStrategy extends AbstractSettleStrategy {
    @Autowired
    private DuesOrderService duesOrderService;
    @Autowired
    private UserService userService;
    @Autowired
    private MerchantService merchantService;

    @Override
    public List<UserBrokerageRecord> settle(String orderNo) {
        List<UserBrokerageRecord> records = Lists.newArrayList();
        DuesOrder duesOrder = duesOrderService.getByOrderNo(orderNo);
        if (duesOrder == null) {
            return records;
        }
        //直接推荐人1%, 间接推荐人0.50%
        SettleRate upgradeSettleRate = SettleRateConfig.getUpgradeSettleRate();

        BigDecimal duesOrderPrice = duesOrder.getPrice();
        if (duesOrderPrice.compareTo(BigDecimal.ZERO) <= 0) {
            log.warn("计算佣金可疑，充值金额为0；duesOrderNo=" + orderNo);
            return records;
        }
        if (duesOrderPrice.compareTo(upgradeSettleRate.getBaseAmount()) < 0) {
            log.warn("计算佣金可疑，充值金额为小于基础金额；duesOrderNo=" + orderNo);
            return records;
        }

        /**
         * 计算充值与基础金额的差值
         */
        BigDecimal subtract = duesOrderPrice.subtract(upgradeSettleRate.getBaseAmount());

        Integer buyerId = duesOrder.getUid();
        if (buyerId == null || buyerId == 0) {
            return records;
        }
        User buyer = userService.getById(buyerId);
        if (buyer == null) {
            return records;
        }
        Integer spreadUid = buyer.getSpreadUid();
        if (spreadUid != null && spreadUid != 0) {
            User spreadUser = userService.getById(spreadUid);
            if (spreadUser != null) {
                //直接推荐人
                if (spreadUser.getFirstPromoter()) {
                    BigDecimal brokerage = SettlementUtil.scale(upgradeSettleRate.getSpread1Amount().add(subtract.multiply(upgradeSettleRate.getSpread1Rate())));
                    UserBrokerageRecord userBrokerageRecord = UserBrokerageRecordBuilder.builder().uid(spreadUid).subUid(buyerId).linkNo(orderNo).linkType(BrokerageRecordConstants.BROKERAGE_RECORD_LINK_TYPE_DUES_ORDER)
                            .type(BrokerageRecordConstants.BROKERAGE_RECORD_TYPE_ADD).title("用户充值直接推荐人获得佣金").price(brokerage).mark(StrUtil.format("用户充值直接推荐人获得佣金，分佣{}", brokerage))
                            // 对于会员额度充值情况，佣金记录状态直接为“冻结期”；
                            .status(BrokerageRecordConstants.BROKERAGE_RECORD_STATUS_FROZEN).frozenTime(0).brokerageLevel(0).build();
                    records.add(userBrokerageRecord);
                }

                if (spreadUser.getSpreadUid() != null && spreadUser.getSpreadUid() != 0) {
                    User secondSpreadUser = userService.getById(spreadUser.getSpreadUid());
                    if (secondSpreadUser != null && secondSpreadUser.getFirstPromoter() && secondSpreadUser.getSecondPromoter()) {
                        //间接推荐人
                        BigDecimal brokerage = SettlementUtil.scale(upgradeSettleRate.getSpread2Amount().add(subtract.multiply(upgradeSettleRate.getSpread2Rate())));
                        UserBrokerageRecord userBrokerageRecord = UserBrokerageRecordBuilder.builder().uid(secondSpreadUser.getId()).subUid(buyerId).linkNo(orderNo).linkType(BrokerageRecordConstants.BROKERAGE_RECORD_LINK_TYPE_DUES_ORDER)
                                .type(BrokerageRecordConstants.BROKERAGE_RECORD_TYPE_ADD).title("用户充值间接推荐人获得佣金").price(brokerage).mark(StrUtil.format("用户充值间接推荐人获得佣金，分佣{}", brokerage))
                                .status(BrokerageRecordConstants.BROKERAGE_RECORD_STATUS_FROZEN).frozenTime(0).brokerageLevel(0).build();
                        records.add(userBrokerageRecord);
                    }
                }
            }
        }

        Integer merId = buyer.getMerId();
        if (merId != null && merId != 0) {
            Merchant merchant = merchantService.getById(merId);
            if (merchant != null) {
                if (merchant.getOwnerUid() != null && merchant.getOwnerUid() != 0) {
                    //店主
//                    BigDecimal brokerage = SettlementUtil.scale(subtract.multiply(upgradeSettleRate.getMerOwnerRate()));
//                    UserBrokerageRecord userBrokerageRecord = UserBrokerageRecordBuilder.builder().uid(merchant.getOwnerUid()).subUid(duesOrder.getUid()).linkNo(orderNo).linkType(BrokerageRecordConstants.BROKERAGE_RECORD_LINK_TYPE_DUES_ORDER)
//                            .type(BrokerageRecordConstants.BROKERAGE_RECORD_TYPE_ADD).title("用户充值店主获得佣金").price(brokerage).mark(StrUtil.format("用户充值店主获得佣金，分佣{}", brokerage))
//                            .status(BrokerageRecordConstants.BROKERAGE_RECORD_STATUS_CREATE).frozenTime(0).brokerageLevel(0).build();
//                    records.add(userBrokerageRecord);
                }

//                if (merchant.getSpreadUid() != null && merchant.getSpreadUid() != 0) {
//                    //店铺推荐人5%
//                    BigDecimal brokerage = SettlementUtil.scale(diff.multiply(orderSettleRate.getMerSpreadRate()));
//                    UserBrokerageRecord userBrokerageRecord = UserBrokerageRecordBuilder.builder().uid(merchant.getSpreadUid()).subUid(order.getUid()).linkNo(orderNo).linkType(BrokerageRecordConstants.BROKERAGE_RECORD_LINK_TYPE_ORDER)
//                            .type(BrokerageRecordConstants.BROKERAGE_RECORD_TYPE_ADD).title("用户下单店铺推荐人获得佣金").price(brokerage).mark(StrUtil.format("用户下单店铺推荐人获得佣金，分佣{}", brokerage))
//                            .status(BrokerageRecordConstants.BROKERAGE_RECORD_STATUS_CREATE).frozenTime(0).brokerageLevel(0).build();
//                    records.add(userBrokerageRecord);
//                }

                if (merchant.getManagerUid() != null && merchant.getManagerUid() != 0) {
                    //店长5%
                    BigDecimal brokerage = SettlementUtil.scale(subtract.multiply(upgradeSettleRate.getMerManagerRate()));
                    UserBrokerageRecord userBrokerageRecord = UserBrokerageRecordBuilder.builder().uid(merchant.getManagerUid()).subUid(duesOrder.getUid()).linkNo(orderNo).linkType(BrokerageRecordConstants.BROKERAGE_RECORD_LINK_TYPE_DUES_ORDER)
                            .type(BrokerageRecordConstants.BROKERAGE_RECORD_TYPE_ADD).title("用户充值店长获得佣金").price(brokerage).mark(StrUtil.format("用户充值店长获得佣金，分佣{}", brokerage))
                            .status(BrokerageRecordConstants.BROKERAGE_RECORD_STATUS_CREATE).frozenTime(0).brokerageLevel(0).build();
                    records.add(userBrokerageRecord);
                }

                // 店铺奖励
                BigDecimal merBrokerage = SettlementUtil.scale(subtract.multiply(upgradeSettleRate.getMerRate()));
                UserBrokerageRecord userBrokerageRecord = UserBrokerageRecordBuilder.builder().uid(0).subUid(0).merId(merId).linkNo(orderNo)
                        .linkType(BrokerageRecordConstants.BROKERAGE_RECORD_LINK_TYPE_DUES_ORDER)
                        .type(BrokerageRecordConstants.BROKERAGE_RECORD_TYPE_ADD).title("用户充值店铺获得佣金").price(merBrokerage).mark(StrUtil.format("用户充值店铺获得佣金，分佣{}", merBrokerage))
                        .status(BrokerageRecordConstants.BROKERAGE_RECORD_STATUS_CREATE).frozenTime(0).brokerageLevel(0).build();
                records.add(userBrokerageRecord);
            }
        }

        //剩余的就是平台所得
        BigDecimal sumPrice = records.stream().map(m -> m.getPrice()).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal platformPrice = subtract.subtract(sumPrice);
        UserBrokerageRecord userBrokerageRecord = UserBrokerageRecordBuilder.builder().uid(0).subUid(0).merId(GlobalConstants.PLATFORM_MER_ID).linkNo(orderNo)
                .linkType(BrokerageRecordConstants.BROKERAGE_RECORD_LINK_TYPE_DUES_ORDER)
                .type(BrokerageRecordConstants.BROKERAGE_RECORD_TYPE_ADD).title("用户充值平台获得佣金").price(platformPrice).mark(StrUtil.format("用户充值平台获得佣金，分佣{}", platformPrice))
                .status(BrokerageRecordConstants.BROKERAGE_RECORD_STATUS_CREATE).frozenTime(0).brokerageLevel(0).build();
        records.add(userBrokerageRecord);
        return records;
    }
}
